package com.example.service.impl;

import cn.hutool.core.date.DateUtil;
import com.example.entity.DownloadLink;
import com.example.mapper.DownloadLinkMapper;
import com.example.service.DownloadLinkService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 下载链接Service实现类
 */
@Service
public class DownloadLinkServiceImpl implements DownloadLinkService {
    
    @Resource
    private DownloadLinkMapper downloadLinkMapper;

    /**
     * 分页查询下载链接
     */
    @Override
    public PageInfo<DownloadLink> page(Integer pageNum, Integer pageSize, Integer versionId, String type) {
        PageHelper.startPage(pageNum, pageSize);
        List<DownloadLink> list = downloadLinkMapper.list(versionId, type);
        return new PageInfo<>(list);
    }

    /**
     * 根据版本ID查询下载链接并按类型分组
     */
    @Override
    public Map<String, List<DownloadLink>> getByVersionId(Integer versionId) {
        List<DownloadLink> links = downloadLinkMapper.list(versionId, null);
        return links.stream().collect(Collectors.groupingBy(DownloadLink::getType));
    }

    /**
     * 根据ID查询下载链接
     */
    @Override
    public DownloadLink getById(Integer id) {
        return downloadLinkMapper.getById(id);
    }

    /**
     * 新增下载链接
     */
    @Override
    public void add(DownloadLink downloadLink) {
        downloadLink.setCreateTime(DateUtil.now());
        downloadLinkMapper.insert(downloadLink);
    }

    /**
     * 批量新增下载链接
     */
    @Override
    @Transactional
    public void batchAdd(List<DownloadLink> downloadLinks) {
        for (DownloadLink link : downloadLinks) {
            link.setCreateTime(DateUtil.now());
            downloadLinkMapper.insert(link);
        }
    }

    /**
     * 更新下载链接
     */
    @Override
    public void update(DownloadLink downloadLink) {
        downloadLinkMapper.update(downloadLink);
    }

    /**
     * 删除下载链接
     */
    @Override
    public void delete(Integer id) {
        downloadLinkMapper.deleteById(id);
    }

    /**
     * 根据版本ID删除所有下载链接
     */
    @Override
    public void deleteByVersionId(Integer versionId) {
        downloadLinkMapper.deleteByVersionId(versionId);
    }
} 